'use client';

import { useClientParams, useGlobalState } from '@/hooks';
import { categoryNameToPathString, staticGo } from '@/utils/common';
//import { useGlobalState } from "@/hooks";
import { Box, Breadcrumbs } from '@mui/material';
import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import './Breadbar.scss';

export default function Breadbar({
  paths,
  basePath,
  crossPage,
}: {
  paths: string[] | Obj[];
  basePath: string;
  crossPage?: boolean;
}) {
  const categoryList: any = useGlobalState('product', 'categoryList');

  const getOriginalPathName = (formatedStr: string) => {
    const cat = categoryList?.find((e: any) => e.url_key == formatedStr);
    return cat ? cat.title : formatedStr;
  };
  const getPathLink = (
    index: number,
    pathArray: string[],
    fn_basePath: string
  ) => {
    if (index == pathArray.length - 1) return '';
    const newBasePath = fn_basePath == 'product' ? 'categories' : fn_basePath;
    return `/${newBasePath}/${pathArray
      .map(p => categoryNameToPathString(p))
      .filter((p, i) => i <= index)
      .join('/')}`;
  };
  const pathsToNodes = (pathArray: any[], fn_basePath: string) => {
    const res = pathArray?.map((path: string, index: number) => {
      if (typeof path == 'object') return path;
      return {
        href: getPathLink(index, pathArray, fn_basePath),
        title: getOriginalPathName(path),
      };
    });
    return res || [];
  };
  const prefixBasePath = (fn_basePath: string) => {
    if (fn_basePath == 'promotion') {
      return {
        href: `/${fn_basePath}`,
        title: 'Promotion',
      };
    } else if (fn_basePath == 'new-arrivals') {
      return {
        href: `/${fn_basePath}`,
        title: 'New Arrivals',
      };
      // } else if (fn_basePath == 'categories') {
      //   return {
      //     href: `/${fn_basePath}`,
      //     title: 'Products',
      //   };
    } else {
      return null;
    }
  };
  const getPathNodesData = (fn_basePath: string, fn_paths: any[]) => {
    const pathNodes = pathsToNodes(fn_paths, fn_basePath);
    const prefixPath = prefixBasePath(fn_basePath);
    prefixPath && pathNodes.unshift(prefixPath);
    return pathNodes;
  };

  const pathsData = getPathNodesData(basePath, paths);

  //=========================================
  const [currPathsData, setCurrPathsData] = useState<any[]>(pathsData);
  const { router, catePaths } = useClientParams();
  const getPathNodesDataRef = useRef(getPathNodesData);
  getPathNodesDataRef.current = getPathNodesData;
  useEffect(() => {
    const currPaths =
      basePath == 'catalogsearch' || basePath == 'product' || basePath == ''
        ? paths
        : catePaths;
    const pathNodesData = getPathNodesDataRef.current(basePath, currPaths);
    setCurrPathsData(pathNodesData);
  }, [basePath, paths, catePaths]);

  const handleBreadClick = (e: any) => {
    e.preventDefault();
    if (crossPage) {
      handleRouterLink(e);
    } else {
      const url = e.currentTarget.href;
      staticGo(url);
    }
  };

  const handleRouterLink = (e: any) => {
    e.preventDefault();
    const url = e.currentTarget.href;
    router.push(url);
  };

  return (
    <div className="bread-bar">
      <Breadcrumbs
        aria-label="breadcrumb"
        className=""
        separator={<span className="iconfont icon-forward-line" />}
      >
        <Link className="bread-bar-item" href="/" onClick={handleRouterLink}>
          <span className="iconfont icon-home"></span>
        </Link>
        {currPathsData?.map((pathData: Obj, index: number) => {
          return (
            <Link
              key={index}
              className="bread-bar-item"
              style={{ color: '#171717' }}
              href={pathData.href}
              onClick={handleBreadClick}
            >
              {pathData.title}
            </Link>
          );
        })}
      </Breadcrumbs>
    </div>
  );
}
